<?php

/**
 * @filesource Communicates with the Student control file to know which student
 * data to get and set. It is the only file that has the SQL queries and MySQL
 * connections
 *
 * @copyright 2011 by Dan, Steven, Brice, Mike, and Aaron.  This program is part
 * of Internship 2 Career, which is free software. It comes with absolutely no
 * warranty. You can redistribute or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation (For
 * more information, see <http://www.gnu.org/licenses/).
 *
 * @version February 10, 2011
 *
 * @author Aaron Jarzombek and Brice Rader
 */
/*
 * This is the database file.
 * It contacts the control file to know
 * which user data to get and set.
 * It is the only file that has the SQL queries and MySQL connections
 *
 */

class dbUser {


    static function createTable() {
        //Create table User
        $query = "
            create table sysuser(
                userID                  int             NOT NULL AUTO_INCREMENT,
                username		varchar(25)	NOT NULL,
                password		varchar(32)	NOT NULL,
                fname                   varchar(25)	NOT NULL,
                lname                   varchar(25)	NOT NULL,
                permissionLevel         text		NOT NULL,
                constraint PK_sysuser PRIMARY KEY (userID)
                );
    ";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }

        //Previous query was successful.
        return true;
    }

    /**
     * Gets all the users from the database.
     * @return object Returns MySql data object
     */
    function getAllUsers() {
        $query = "SELECT * FROM sysuser";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful
        return $result;
    }

    /**
     * Updates user information
     * @param object $user Class user
     * @return int Returns 0 if there was an error updating, else returns 1.
     */
    function updateUser($u) {
        if (!($u instanceof User)) {
            return false;
        }
        $userID = $u->getUserID();
        $username = $u->getUsername();
        $password = $u->getPassword();
        $fname = $u->getFName();
        $lname = $u->getLName();
        $permissionlevel = $u->getPermissionLevel();

        if ($username != '') {
            $success *= mysql_query("UPDATE sysuser SET username='$username' 
                    WHERE userID=$userID");
        }
        if ($password != '') {
            $success *= mysql_query("UPDATE sysuser SET password='$password' 
                    WHERE userID=$userID");
        }
        if ($fname != '') {
            $success *= mysql_query("UPDATE sysuser SET fname='$fname' WHERE
                    userID=$userID");
        }
        if ($lname != '') {
            $success *= mysql_query("UPDATE sysuser SET lname='$lname' WHERE
                    userID=$userID");
        }
        if ($permissionlevel != '') {
            $success *= mysql_query("UPDATE sysuser SET
                    permissionlevel='$permissionlevel' WHERE userID=$userID");
        }
        return true;
    }

    /**
     * Adds a contact to the database.
     * @param object $user Class  User
     * @return bool Returns TRUE if query completes successfully.
     */
    static function addUser($u, &$id) {
        if (!$u instanceof User) {
            echo ("Invalid argument addUser() function<br />");
            return false;
        }

        //Compose the ADD query string. Primary key value is missing.
        //Database server automatically generates a unique ID for the primary
        //key.
        $query = sprintf("INSERT INTO sysuser VALUES (null,'%s', '%s', '%s', 
            '%s', '%s')",
                        $u->getUsername(),
                        $u->getPassword(),
                        $u->getFname(),
                        $u->getLname(),
                        $u->getPermissionLevel()
        );
        connectToDatabase();
        $result = mysql_query($query);
        $id = mysql_insert_id();
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }

        //Query was successful.
        printf("User added has id %d\n<br />", mysql_insert_id());
        return true;
    }
	
	/**
	* @param getUserID $u
	* @return returns user ID
	*/
    function getUserID($u) {
        $result = mysql_query("SELECT userID FROM sysuser WHERE
            userID='$u'");
        $row = mysql_fetch_row($result);
        return $row['0'];
    }

	/**
	* Gets user name from sysuser
	* @param getUsername $u
	* @return object returns user name
	*/
    function getUsername($u) {
        $query = "SELECT username FROM sysuser
        WHERE userID='$u'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets password from sysuser
	* @param getPassword $u
	* @return object returns password
	*/
    function getPassword($u) {
        $query = "SELECT password FROM sysuser
        WHERE userID='$u'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets first name from sysuser
	* @param getFname $u
	* @return object returns first name
	*/
    function getFname($u) {
        $query = "SELECT username FROM sysuser
        WHERE userID='$u'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets last name from sysuser
	* @param getLname $u
	* @return object returns last name
	*/
    function getLname($u) {
        $query = "SELECT lname FROM sysuser
        WHERE userID='$u'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

	/**
	* Gets permission level from sysuser
	* @param getPermissionLevel $u
	* @return object returns permission level
	*/
    function getPermissionLevel($u) {
        $query = "SELECT permissionLevel FROM sysuser
        WHERE userID='$u'";
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }
        //Query was successful.
        return $result;
    }

    /**
     * Checks to see if the ID exists.
     * @param object $user Class User
     * @return int Returns FALSE if the ID cannot be found, and TRUE if the ID
     * is found
     */
    function checkID($u) {
        if (!($u instanceof User)) {
            return false;
        }
        $userID = $u->getUserID();
        if (mysql_num_rows(mysql_query("SELECT * FROM sysuser WHERE
                userID=$userID")) == 0) {
            //nothing exists mysql_num_rows
            return false;
        } else {
            return true;
        }
    }

    /**
     * Gets all the user information for a user with a certain ID.
     * @param int $username ID of user you want to get.
     * @return object Returns FALSE if ID does not exist, or a USer object if
     * it does.
     */
    function getUser($username) {
        $user = new User();
        $result = mysql_query("SELECT * FROM sysuser WHERE username=
                '$username'");
        if (!$result) {
            return false; //username does not exist
        } else {
            $row = mysql_fetch_assoc($result);
            $user->setUserName($username);
            $user->setPassword($row['password']);
            $user->setFName($row['fname']);
            $user->setLName($row['$lname']);
            $user->setPermissionLevel($row['permissionlevel']);
            return $u;
        }
    }

    /**
     * Deletes a user from the database.
     * @param object $user Class User
     * @return bool Returns TRUE if user can be deleted.
     */
    function deleteUser($u) {

        if (!$u instanceof user) {
            echo ("Invalid argument deleteFrom() function<br />");
            return false;
        }

        //Compose the DELETE FROM query string.
        $query = sprintf("DELETE FROM sysuser WHERE username = '%s'",
                        $u->getUsername()
        );
        connectToDatabase;
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error();
            return false;
        }

        //Query was successful.
        return true;
    }
public static function getAllByID($id, &$output) {
        $query = sprintf("SELECT username, password, fname,
            lname, permissionlevel FROM sysuser WHERE
            username=%d", $username);
        //printf("->Query: %s<br />", $query);
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();

        if ($result == false) {
            $output = sprintf("%s", mysql_error());
            return false;
        }
        //process result and print out warning or attribute values
        return dbUser::checkForOneInstance($result, $id, $output);
    }

    private static function checkForOneInstance($result, $id, &$output) {
        //Local variables are initialized.
        $errorStatus = false;

        $howMany = mysql_num_rows($result);
        printf("->Found %d instance(s) for userID=%d.<br />", $howMany, $id);
        switch ($howMany) {
            case 0:
                $output = sprintf("No User instance with ID=%d was found.",
                                $id);
                $errorStatus = true;
                break;
            case 1:
                //mysql_fetch() DOES NOT return primary key values
                $output = mysql_fetch_assoc($result);
                $errorStatus = false;
                break;
            default:
                $output = sprintf("There are multiple user instances with
                                  ID=%d.", $id);
                $errorStatus = true;
                break;
        }
        return $errorStatus;
    }

}

?>
